//
//  ViewController.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/3.
//  Copyright © 2020 com.example. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let config = WKWebViewConfiguration()
        let birdge = BridgeHandler()
        config.userContentController.add(birdge, name: "iOSBridge")
        
        webView = WKWebView(frame: self.view.frame, configuration: config)
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        birdge.webView = webView
        
        let url = Bundle.main.url(forResource: "test", withExtension: "html")!
        webView.loadFileURL(url, allowingReadAccessTo: url)
    }
}

class BridgeHandler : NSObject, WKScriptMessageHandler {
    
    var webView: WKWebView!
    
    func userContentController(
        _ userContentController: WKUserContentController,
        didReceive message: WKScriptMessage)
    {
        let body = message.body as! [String: Any]
        print("WebView callNative ok. body is \(body)")
        print("WebView arg name=\(body["name"]!)")
        
        webView.evaluateJavaScript("onNativeResult('Native callback ok.')") { _, _ in }
    }
}

